package com.lc.zpyh.adapter;

import android.os.CountDownTimer;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.lc.zpyh.R;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class CountDownAdapter extends BaseQuickAdapter<CountDownEntity, CountDownAdapter.MyViewHolder> {

    //退出activity时关闭所有定时器，避免造成资源泄漏。
    private SparseArray<CountDownTimer> countDownMap = new SparseArray<>();
    //记录每次刷新时的时间
    private long tempTime;

    public CountDownAdapter(@Nullable List<CountDownEntity> data) {
        super(R.layout.item_main, data);
    }

    @Override
    protected void convert(@NonNull MyViewHolder baseViewHolder, CountDownEntity countDownEntity) {
        baseViewHolder.setGone(R.id.tvTime, !countDownEntity.getTimev());
        baseViewHolder.setText(R.id.tvTitle, countDownEntity.getTitle());

        long timeStamp = System.currentTimeMillis() - tempTime;
        long time = countDownEntity.getTime() - timeStamp;

        if (baseViewHolder.countDownTimer != null) {
            baseViewHolder.countDownTimer.cancel();
        }

        if (time > 0) {
            baseViewHolder.countDownTimer = new CountDownTimer(time, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    baseViewHolder.setText(R.id.tvTime, getShowStr(millisUntilFinished));
                }

                @Override
                public void onFinish() {
                    baseViewHolder.setGone(R.id.tvTime, true);
                }
            };
            baseViewHolder.countDownTimer.start();
            countDownMap.put(countDownEntity.getId(), baseViewHolder.countDownTimer);
            Log.e("TAG", "convert: "+ countDownMap.size());
        }else {
            baseViewHolder.setText(R.id.tvTime, "完");
        }

    }

    private String getShowStr(long mis) {
        mis = mis / 1000; //
        long h = mis / 3600;
        long m = mis % 3600 / 60;
        long d = mis % 3600 % 60;
        return h + ":" + m + ":" + d;
    }

    public void setGetTime(long tempTime) {
        this.tempTime = tempTime;
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }
        for (int i = 0, length = countDownMap.size(); i < length; i++) {
            CountDownTimer cdt = countDownMap.get(countDownMap.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }

    public static class MyViewHolder extends BaseViewHolder {

        public CountDownTimer countDownTimer;

        public MyViewHolder(@NonNull View view) {
            super(view);
        }
    }
}
